﻿using AutoMapper;
using JuCheap.Core.IService;
using JuCheap.Core.Model;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using JuCheap.Core.Infrastructure.Extentions;
using System.Linq;

namespace JuCheap.Core.WebApi.Controllers
{
    /// <summary>
    /// 升级日志服务api
    /// </summary>
    [Route("api/[controller]")]
    public class UpgradeLogController : BaseApiController
    {
        private readonly ISysUpgradeLogQueryService _upgradeLogQueryService;
        private readonly ISysUpgradeLogService _sysUpgradeLogService;
        private readonly ISysUpgradeLogDetailService _sysUpgradeLogDetailService;
        private readonly IMapper _mapper;

        /// <summary>
        /// ctor
        /// </summary>
        public UpgradeLogController(ISysUpgradeLogQueryService upgradeLogQueryService,
            ISysUpgradeLogService sysUpgradeLogService,
            ISysUpgradeLogDetailService sysUpgradeLogDetailService,
            IMapper mapper)
        {
            _upgradeLogQueryService = upgradeLogQueryService;
            _sysUpgradeLogService = sysUpgradeLogService;
            _sysUpgradeLogDetailService = sysUpgradeLogDetailService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取最近的100条升级日志
        /// </summary>
        [HttpGet]
        [Route("top-100")]
        public async Task<ActionResult<IEnumerable<UpgradeLogResponseDto>>> SearchUpgradeLogs()
        {
            var records = await _upgradeLogQueryService.QueryTopAsync();
            return Ok(records);
        }

        /// <summary>
        /// 添加升级日志
        /// </summary>
        [HttpPost]
        [Route("create")]
        public async Task<ActionResult<IEnumerable<UpgradeLogResponseDto>>> Add([FromBody]UpgradeLogAddDto req)
        {
            var info = _mapper.Map<SysUpgradeLogDto>(req);
            var logId = await _sysUpgradeLogService.InsertAsync(info);
            if (req.Details.IsNotBlank())
            {
                var details = req.Details.Split(new[] { '\r', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
                var logDetails = details.Select(x => new SysUpgradeLogDetailDto { LogId = logId, Detail = x }).ToList();
                await _sysUpgradeLogDetailService.BatchInsertAsync(logDetails);
            }
            return Ok(true);
        }
    }
}
